********************************************************************************
** 	TITLE:		whole_results                                                 ** 	
**  AUTHOR:	    Philippe Mongrain                                             **
**	DATA:       whole_results		                                          **
**	DATE:		October 2022 						                          **	
**  VERSION:	Stata 16					                                  **	
********************************************************************************

* Version control

version 16.0

* Open the dataset

use "whole_results.dta", clear

* Generate rank of parties

gsort code election_type house -votes
bysort code election_type house : gen rank = _n

gen first = party if rank == 1
gen second = party if rank == 2
gen third = party if rank == 3

bysort code election_type house : gen winner = first[1] // Popular vote winner
bysort code election_type house : gen runnerup = second[2]
bysort code election_type house : gen thirdplace = third[3]

* Generate margins of victory

bysort code election_type house : gen margin_w = percentvotes[1] - percentvotes[2]

* Generate effective number of electoral parties

gen sqrvotepr = (percentvotes/100)^2

bysort code election_type house : egen sumsqrvotepr = sum(sqrvotepr)

gen enep_w = 1/sumsqrvotepr

* Selecting, ordering, and sorting variables

keep code region unit election_level election_type house party rank votes percentvotes seats percentseats margin_w enep_w winner runnerup thirdplace

order code region unit election_level election_type house party rank votes percentvotes seats percentseats margin_w enep_w winner runnerup thirdplace

drop if rank > 3

* Drop duplicates

duplicates tag code election_type house, gen(dup)
duplicates drop code election_type house, force
drop dup

* Saving file

save margin_enep_w, replace